package com.example.teaching_server.service;

import com.example.teaching_server.dto.SidebarItemDTO;
import com.example.teaching_server.entity.Category;
import com.example.teaching_server.entity.CourseItem;
import com.example.teaching_server.entity.CourseEntity;
import com.example.teaching_server.repository.CategoryRepository;
import com.example.teaching_server.repository.CourseItemRepository;
import com.example.teaching_server.repository.CourseRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 课程管理服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class CourseService {

    private final CategoryRepository categoryRepository;
    private final CourseItemRepository courseItemRepository;
    private final CourseRepository courseRepository;

    /**
     * 获取侧边栏项目
     */
    public List<SidebarItemDTO> getSidebarItems(String type) {
        log.info("获取侧边栏项目: type={}", type);

        if (type == null || type.trim().isEmpty()) {
            log.warn("侧边栏类型为空，返回空列表");
            return Collections.emptyList();
        }

        List<Category> categories = categoryRepository.findByCategoryType(type);

        return categories.stream()
                .map(this::convertCategoryToSidebarItem)
                .sorted(Comparator.comparing(SidebarItemDTO::getSortOrder))
                .collect(Collectors.toList());
    }

    /**
     * 获取所有课程
     */
    public List<CourseEntity> getAllCourses() {
        log.info("获取所有课程");
        return courseRepository.findAllByOrderByCourseNameAsc();
    }

    /**
     * 按类别获取课程
     */
    public List<CourseEntity> getCoursesByCategory(String category) {
        log.info("按类别获取课程: category={}", category);
        if (category == null || category.trim().isEmpty()) {
            return Collections.emptyList();
        }
        return courseRepository.findByCategoryOrderByCourseNameAsc(category);
    }

    /**
     * 获取所有课程分类
     */
    public List<Map<String, Object>> getAllCourseCategories() {
        log.info("获取所有课程分类");

        List<CourseEntity> allCourses = courseRepository.findAll();

        Map<String, List<Map<String, Object>>> groupedByCategory = allCourses.stream()
                .filter(course -> course.getCategory() != null && !course.getCategory().trim().isEmpty())
                .collect(Collectors.groupingBy(
                        CourseEntity::getCategory,
                        Collectors.mapping(this::convertCourseToInfoMap, Collectors.toList())
                ));

        return groupedByCategory.entrySet().stream()
                .map(this::convertCategoryEntryToMap)
                .sorted(Comparator.comparing(info -> (String) info.get("category")))
                .collect(Collectors.toList());
    }

    /**
     * 获取简单课程分类列表
     */
    public List<String> getSimpleCourseCategories() {
        log.info("获取简单课程分类列表");
        return courseRepository.findAll()
                .stream()
                .map(CourseEntity::getCategory)
                .filter(category -> category != null && !category.trim().isEmpty())
                .distinct()
                .sorted()
                .collect(Collectors.toList());
    }

    /**
     * 根据ID获取课程
     */
    public Optional<CourseEntity> getCourseById(Long courseId) {
        log.info("根据ID获取课程: courseId={}", courseId);
        if (courseId == null || courseId <= 0) {
            return Optional.empty();
        }
        return courseRepository.findById(courseId);
    }

    /**
     * 搜索课程
     */
    public List<CourseEntity> searchCourses(String keyword) {
        log.info("搜索课程: keyword={}", keyword);
        if (keyword == null || keyword.trim().isEmpty()) {
            return Collections.emptyList();
        }

        return courseRepository.findAllByOrderByCourseNameAsc().stream()
                .filter(course -> course.getCourseName() != null &&
                        course.getCourseName().toLowerCase().contains(keyword.toLowerCase()))
                .collect(Collectors.toList());
    }

    /**
     * 获取热门课程
     */
    public List<CourseEntity> getPopularCourses(int limit) {
        log.info("获取热门课程: limit={}", limit);
        if (limit <= 0) {
            limit = 10;
        }
        List<CourseEntity> allCourses = courseRepository.findAllByOrderByCourseNameAsc();
        return allCourses.stream()
                .limit(limit)
                .collect(Collectors.toList());
    }

    /**
     * 获取课程统计信息
     */
    public Map<String, Object> getCourseStatistics() {
        log.info("获取课程统计信息");
        List<CourseEntity> allCourses = courseRepository.findAll();

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalCourses", allCourses.size());

        Map<String, Long> categoryStats = allCourses.stream()
                .filter(course -> course.getCategory() != null && !course.getCategory().trim().isEmpty())
                .collect(Collectors.groupingBy(CourseEntity::getCategory, Collectors.counting()));
        stats.put("categoryStats", categoryStats);

        return stats;
    }

    /**
     * 将分类转换为侧边栏项目
     */
    private SidebarItemDTO convertCategoryToSidebarItem(Category category) {
        List<CourseItem> items = courseItemRepository.findByCategoryId(category.getId());

        List<SidebarItemDTO.SubItemDTO> subItems = items.stream()
                .map(this::convertItemToSubItemDTO)
                .collect(Collectors.toList());

        return SidebarItemDTO.builder()
                .id(category.getId())
                .name(category.getName())
                .icon(category.getIcon())
                .route(buildCategoryRoute(category))
                .expanded(false)
                .sortOrder(getCategorySortOrder(category))
                .enabled(isCategoryEnabled(category))
                .children(subItems)
                .build();
    }

    /**
     * 将课程项转换为子项DTO
     */
    private SidebarItemDTO.SubItemDTO convertItemToSubItemDTO(CourseItem item) {
        return SidebarItemDTO.SubItemDTO.builder()
                .id(item.getId())
                .name(item.getName())
                .icon(item.getIcon())
                .route(buildItemRoute(item))
                .sortOrder(getItemSortOrder(item))
                .enabled(isItemEnabled(item))
                .build();
    }

    /**
     * 将课程转换为信息映射
     */
    private Map<String, Object> convertCourseToInfoMap(CourseEntity course) {
        Map<String, Object> courseInfo = new HashMap<>();
        courseInfo.put("courseId", course.getCourseId());
        courseInfo.put("courseName", course.getCourseName());
        courseInfo.put("credit", course.getCredit());
        return courseInfo;
    }

    /**
     * 将分类条目转换为映射
     */
    private Map<String, Object> convertCategoryEntryToMap(Map.Entry<String, List<Map<String, Object>>> entry) {
        Map<String, Object> categoryInfo = new HashMap<>();
        categoryInfo.put("category", entry.getKey());
        categoryInfo.put("courses", entry.getValue());
        categoryInfo.put("courseCount", entry.getValue().size());
        return categoryInfo;
    }

    // 辅助方法保持不变
    private String buildCategoryRoute(Category category) {
        if (category == null) return "/";
        return "/category/" + category.getId();
    }

    private String buildItemRoute(CourseItem item) {
        if (item == null) return "/";
        return "/item/" + item.getId();
    }

    private Integer getCategorySortOrder(Category category) {
        if (category == null) return 999;
        return category.getId();
    }

    private Integer getItemSortOrder(CourseItem item) {
        if (item == null) return 999;
        return item.getId();
    }

    private Boolean isCategoryEnabled(Category category) {
        if (category == null) return false;
        return true;
    }

    private Boolean isItemEnabled(CourseItem item) {
        if (item == null) return false;
        return true;
    }
}
